<?php

namespace app\model;

use think\Db;

class PassportCommon extends Common
{
    protected static $obj;

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 类入口
     * @return PassportCommon
     */
    public static function getInstance()
    {
        if (is_null(self::$obj))
            self::$obj = new self();
        return self::$obj;
    }

    /**
     * 获取编号
     * @param $str_passport
     * @param $str_platform
     * @param $int_id_name
     * @return bool|int
     */
    public function getId($str_passport, $str_platform, $int_id_name)
    {
        $int_id = $this->toValue(['passport' => $str_passport, 'platform' => $str_platform], $int_id_name);
        if (isset($int_id) && $int_id > 0) {
            $str_last_passport = $this->getPassport($int_id, $str_platform, $int_id_name);
            if ($str_last_passport == $str_passport) {
                return (int)$int_id;
            }
        }
        return false;
    }

    /**
     * 获取最新的登录票据
     * @param int $int_id 用户编号
     * @param string $str_platform 来自平台 web-网页 app-移动端 api-接口 wechat-微信端
     * @param string $int_id_name 相关的键值
     * @param bool $bool_is_add 是否添加新的passport
     * @return string
     */
    public function getPassport($int_id, $str_platform, $int_id_name, $bool_is_add = false)
    {
        if ($bool_is_add === true) {
            $passport = $this->addUserPassportInfo($int_id, $str_platform, $int_id_name);
        } else {
            $passport = (string)Db::table($this->db_name)->where([$int_id_name => $int_id, 'platform' => $str_platform])->order('id DESC')->value('passport');
            if (!(strlen($passport) > 10)) {
                $this->addUserPassportInfo($int_id, $str_platform, $int_id_name);
            }
        }
        return $passport;
    }

    /**
     * 获取最新的登录票据
     * @param int $int_id 用户编号
     * @param string $str_platform 来自平台 web-网页 app-移动端 api-接口 wechat-微信端
     * @param string $int_id_name 相关的键值
     * @return bool|string
     */
    public function getNewPassport($int_id, $int_id_name)
    {
        $passport = (string)Db::table($this->db_name)->where([$int_id_name => $int_id, 'platform' => 'app'])->order('id DESC')->value('passport');
        if (!(strlen($passport) > 10)) {
            return false;
        }
        return $passport;
    }

    /**
     * 添加登录票据
     * @param int $user_id 用户编号
     * @param string $platform 来自平台 web-网页 api-接口
     * @param string $int_id_name 相关的键值
     * @return string
     */
    public function addUserPassportInfo($int_id, $str_platform, $int_id_name)
    {
        $passport = createPassport();
        $this->toAdd([
            $int_id_name => $int_id,
            'passport' => $passport,
            'platform' => $str_platform,
            'ip' => $this->getIP(),
            'gmt_modified' => $this->_now,
            'gmt_create' => $this->_now,
        ]);
        return $passport;
    }
}
